package com.comp6231.replica1.server;

import java.net.*;
import java.io.*;


import com.comp6231.replica1.data.Stations;

/**
 * 
 * @author sknarula (narula.sk@gmail.com)
 * @since	September 2013
 * 
 * This is the DPIS server system's class to interact with 
 * other servers responsible to reply with the number of 
 * records in the hashtable associated with the given server
 * 
 */
public class StationServerToServerInterface extends Thread {

	/**
	 * 
	 */
	StationServerImplementation server = null;
	int portNum;

	public StationServerToServerInterface (StationServerImplementation server) {
		this.server = server;
		this.portNum = Stations.getEnumValue(server.getStationName()).getPoliceStationUdpValue();
	}
	
	public void run() {
		DatagramSocket aSocket = null;
		try{
			aSocket = new DatagramSocket(this.portNum);
			byte[] buffer = new byte[1000];
			while(true){
				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
				aSocket.receive(request); 
				buffer = String.valueOf(this.server.getTotalRecords()).getBytes();
				DatagramPacket reply = new DatagramPacket(buffer, 
						buffer.length, request.getAddress(), request.getPort());
				aSocket.send(reply);
			}
		} catch (SocketException e) {
			System.out.println("Socket: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("IO: " + e.getMessage());
		} finally {
			if(aSocket != null) 
				aSocket.close();
		}
		
	}
}
